import datetime
import random
import string
import time
from django.http import JsonResponse
from tools.Tools import res, token_all_current, token_expired_time, token_username, username_token


def generateToken(username):
    """
    生成随机token
    :return: 64位 random token
    """
    # 清理username原token，防止异地登录
    previousToken = username_token.get(username, None)
    if previousToken is not None:
        token_all_current.remove(previousToken)
        token_username.pop(previousToken)
        token_expired_time.pop(previousToken)

    length = 64
    chars = (string.ascii_letters + string.ascii_lowercase + string.digits).lower()
    # tokenList = [random.choice(chars) for _ in range(length)]
    token = "".join([random.choice(chars) for _ in range(length)])  # 随机token
    token_expiredTime = generateTokenExpiredTime()  # 过期时间
    token_all_current.add(token)
    token_username[token] = username
    token_expired_time[token] = token_expiredTime
    # current_user_token_list = list(filter(lambda k: token_username[k] == username, token_username))
    username_token[username] = token
    return token


def generateTokenExpiredTime():
    """
    生成过期时间：当前时间 + 两个小时 expired=time_now+datetime.timedelta(hours=2)
    :return:int(time)
    """
    expiredTime = datetime.datetime.now() + datetime.timedelta(hours=2)
    expiredTime = time.mktime(expiredTime.timetuple())
    expiredTime = int(expiredTime)
    return expiredTime


# todo 验证 token
def isTokenExpired(token):
    """
    check token timeliness
    :param token:
    :return: true or false
    """
    try:
        if token in token_expired_time.keys():
            tokenExpiredTime = token_expired_time[token]
            timeNow = datetime.datetime.now()
            timeNow = time.mktime(timeNow.timetuple())
            timeNow = int(timeNow)
            if tokenExpiredTime - timeNow < 0:
                # todo 清理过期token
                return True
            else:
                updateTokenExpiredTime(token)
                return False
        else:
            res['status'] = 400
            res['msg'] = 'token已失效！'
            return JsonResponse(res)
    except Exception as e:
        print(e)
        return True


def updateTokenExpiredTime(token):
    """
    update token time of two hours
    :param token:
    :return: int update token time
    """
    token_expired = generateTokenExpiredTime()  # 产生过期时间

    token_expired_time[token] = token_expired  # token 过期时间
    return
